package com.krlin.word.word.service.impl;

import com.krlin.word.word.dao.WordDao;
import com.krlin.word.word.pojo.WordEntity;
import com.krlin.word.word.service.WordMongoService;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;
import java.util.regex.Pattern;

import static org.springframework.data.mongodb.core.query.Criteria.where;

/**
 * @author krlin
 */
@Service
public class WordMongoServiceImpl implements WordMongoService {

    @Resource
    private WordDao wordDao;

    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public List<WordEntity> findWordList() {
        return wordDao.findAll();
    }

    @Override
    public WordEntity findOneWordByRand() {
        int wordCount = Math.toIntExact(getWordNum());
        Integer randId = new Random().nextInt(wordCount + 1);
        return mongoTemplate.findOne(new Query(where("word_id").is(randId)), WordEntity.class);
    }

    @Override
    public List<WordEntity> findWordsByType(String type) {
        Pattern pattern = Pattern.compile("^"+type+"", Pattern.CASE_INSENSITIVE);
        return mongoTemplate.find(new Query(where("word").regex(pattern)), WordEntity.class);
    }

    @Override
    public WordEntity saveOneWord(WordEntity wordEntity) {
        return wordDao.save(wordEntity);
    }

    @Override
    public List<WordEntity> saveWords(List<WordEntity> list) {
        return wordDao.saveAll(list);
    }

    private Long getWordNum() {
        return wordDao.count();
    }
}
